<template>
  <div>
    <el-form  style="margin-left: 10px;">
      <el-form-item label="切换项目" prop="id" style="padding-top: 15px;">
        <el-select v-model="logstoreName" placeholder="请选择项目"
          @change="handleStoreChange(logstoreName)">
          <el-option v-for="item in logstores" :key="item.data" :label="item.data" :value="item.data">
          </el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <el-form :inline="true" :model="searchParams" class="demo-form-inline" style="margin-left: 10px;">
      <el-form-item label="deviceId">
        <el-input v-model="searchParams.deviceId" placeholder="设备ID" style="width:400px" clearable></el-input>
      </el-form-item>
      <el-form-item label="deviceCode">
        <el-input v-model="searchParams.deviceCode" placeholder="设备编码" style="width:220px" clearable></el-input>
      </el-form-item>
      <el-form-item label="关键字">
        <el-input v-model="searchParams.query" placeholder="关键字" style="width:250px" clearable></el-input>
      </el-form-item>
      <el-form-item label="等级" prop="level" >
        <el-select v-model="level" placeholder="请选择等级"   clearable="">
          <el-option v-for="item in levelList" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <el-form style="margin-left: 10px;" :inline="true" :model="searchParams" class="demo-form-inline">
      <el-form-item label="时间选择">
        <el-date-picker v-model="searchParams.dateTime" type="datetimerange" :picker-options="pickerOptions"
          range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期">
        </el-date-picker>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="queryByForm" style="margin-left: 20px;">查询</el-button>
      </el-form-item>
    </el-form>
    <el-table v-loading="listLoading" :data="list" style="width: 100%">
      <el-table-column label="deviceId" width="100" prop="deviceId" align="center"></el-table-column>
      <el-table-column label="deviceCode" width="200" prop="deviceCode" align="center"></el-table-column>
      <el-table-column label="等级" prop="level" width="100" align="center"></el-table-column>
      <el-table-column label="上报时间" width="200" prop="currentTime" align="center">
        <template slot-scope="scope">
          {{ scope.row.currentTime || formatDate }}
        </template>
      </el-table-column>
        <el-table-column label="TAG" prop="tag" width="100" align="center"></el-table-column>
      <el-table-column label="设备操作详情"  prop="content" align="left"></el-table-column>
      
    </el-table>
    <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
      :current-page="slsOptions.offset + 1" :page-size="slsOptions.line" :page-sizes="[20, 50]"
      layout="total, sizes, prev, pager, next,jumper" :total="total">
    </el-pagination>
  </div>
</template>
    
<script>
import {
  getProjectList,
} from '@/api/sku/sku'
//import { deviceListRemoteControl } from '@/api/device/deviceModel'
import { slsParams, getSign, getGMTTime } from '@/utils/slsLogsUrl'
import { getLogStores } from "./api.js"
import moment from 'moment'
//import ALY from 'aliyun-sdk'
export default {
  props: ['row', 'userId'],
  data() {
    return {
      // 日期选择器配置
      pickerOptions: {
        shortcuts: [
        {
            text: '1分钟',
            onClick(picker) {
              const start = new Date()
              const end = new Date()
              const startTime = moment(moment().startOf('minute').valueOf())
              const endTime = moment(moment().endOf('minute').valueOf())
              start.setTime(startTime)
              end.setTime(endTime)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '5分钟',
            onClick(picker) {
              const start = new Date()
              const end = new Date()
              const startTime = moment(moment().subtract(4, 'minute').startOf('minute').valueOf())
              const endTime = moment(moment().endOf('minute').valueOf())
              start.setTime(startTime)
              end.setTime(endTime)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '15分钟',
            onClick(picker) {
              const start = new Date()
              const end = new Date()
              const startTime = moment(moment().subtract(14, 'minute').startOf('minute').valueOf())
              const endTime = moment(moment().endOf('minute').valueOf())
              start.setTime(startTime)
              end.setTime(endTime)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '1小时',
            onClick(picker) {
              const start = new Date()
              const end = new Date()
              const startTime = moment(moment().startOf('hour').valueOf())
              const endTime = moment(moment().endOf('hour').valueOf())
              start.setTime(startTime)
              end.setTime(endTime)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '4小时',
            onClick(picker) {
              const start = new Date()
              const end = new Date()
              const startTime = moment(moment().subtract(3, 'hour').startOf('hour').valueOf())
              const endTime = moment(moment().endOf('hour').valueOf())
              start.setTime(startTime)
              end.setTime(endTime)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '今天',
            onClick(picker) {
              const start = new Date()
              const end = new Date()
              const startTime = moment(moment().startOf('day').valueOf())
              const endTime = moment(moment().endOf('day').valueOf())
              start.setTime(startTime)
              end.setTime(endTime)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '昨天',
            onClick(picker) {
              const start = new Date()
              const end = new Date()
              const startTime = moment(moment().subtract(1, 'day').startOf('day').valueOf())
              const endTime = moment(moment().subtract(1, 'day').endOf('day').valueOf())
              start.setTime(startTime)
              end.setTime(endTime)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近7天',
            onClick(picker) {
              const start = new Date()
              const end = new Date()
              const startTime = moment(moment().subtract(6, 'day').startOf('day').valueOf())
              const endTime = moment(moment().endOf('day').valueOf())
              start.setTime(startTime)
              end.setTime(endTime)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近一个月',
            onClick(picker) {
              const start = new Date()
              const end = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
              picker.$emit('pick', [start, end])
            }
          }
        ]
      },
      searchParams: {
        deviceCode: '',
        deviceId: '',
        query: '',
        dateTime: []
      },
      logstoreName: 'wahaha',
      slsLogDialog: false, // 弹窗
      slsOptions: { //options参数配置
        progress: '',    //必选参数,project名称
        logStoreName: '',    //必选参数,logStore名称,项目对应的数据库名
        from: '',    //必选参数, 开始时间(精度为秒,从 1970-1-1 00:00:00 UTC 计算起的秒数)
        to: '',      //必选参数,结束时间(精度为秒,从 1970-1-1 00:00:00 UTC 计算起的秒数)
        topic: '',   //可选参数,指定日志主题(用户所有主题可以通过listTopics获得)
        query: '',  //查询的关键词,不输入关键词,则查询全部日志数据
        line: 20,    //读取的行数,默认值为 100,取值范围为 0-100
        offset: 0,   //读取起始位置,默认值为 0,取值范围>0
        url: '',
        date: '',
        params: '',
        accessKeyId: '',
        sign: ''
      },
      listLoading: false,//加载
      list: [],
      levelList:[{
        value: 'debug',
        label: '正常'
      }, {
        value: 'info',
        label: '警告'
      }, {
        value: 'error',
        label: '错误'
      }],
      level:'',
      activeName: 'first',
      pageSize: 20,
      pageNum: 1,
      total: 0,
      queryParams: {
        title: ''
      },
      projectList: {}, //获取到的项目列表
      logstores: [],

    }
  },
  mounted() {

  },
  created() {
    this.getDate()
    this.queryByForm()
    this.getProject()
  },
  methods: {
    /**默认时间 */
    getDate() {
      const start = new Date()
      const end = new Date()
      const startTime = moment(moment().startOf('day').valueOf())
      const endTime = moment(moment().endOf('day').valueOf())
      start.setTime(startTime)
      end.setTime(endTime)
      this.searchParams.dateTime = [start, end]
      //picker.$emit('pick', [start, end])
    },
    handleLevelChangev(val){
      console.log('%%%',val);
      
    },
    handleStoreChange(val) {
      this.logstoreName = val;
      this.calOpt()
      this.getTotal()
      this.getData()
    },


    /**获取项目 */
    getProject() {
      let _this = this;
      let data = {}
      let signParam = {};
      data.date = getGMTTime()
      data.url = "/logstores"
      //排序
      data.params = "?offset=0&size=50"
      signParam.verb = "GET"
      signParam.canonicalizedResource = data.url + data.params
      signParam.date = data.date
      let sign = getSign(signParam);
      data.accessKeyId = slsParams().accessKeyId
      data.sign = sign

      getLogStores(data).then(res => {
        let temp = res.data.logstores
        if (temp && temp.length) {
          temp.forEach(e => {
            _this.logstores.push({ data: e })
          });
          console.log('#####', this.logstores);

        }
      }).catch(err => {
        // console.log(err)
        showMessage(_this, "获取Logstore错误：" + err, "error")
      });

      // let params = {
      //   offset: 0,
      //   size:50,
      // }
      // getProjectList(params).then((res) => {
      //   if (res.code === 200) {
      //     this.projectList = res.rows
      //     // for (var i = 0; i < res.rows.length; i++) {
      //     //   this.projectName.push(res.rows[i].projectName)
      //     // }
      //   }
      // })
    },
    /** 点击搜索 */
    queryByForm() {
      console.log('#####!!!!',this.searchParams)
      if (!this.searchParams.dateTime || !this.searchParams.dateTime[0] || !this.searchParams.dateTime[1]) {
        this.$message.warning("请选择起始日期")
        return
      } else {
        this.calOpt()
        this.getTotal()
        this.getData()
      }
    },
    calSqlPre() {
      //todo 拼接查询参数
      if(this.$route.query.deviceId){
        this.searchParams.deviceId = this.$route.query.deviceId
      }
      let sqlPre = ""
      sqlPre += this.searchParams.deviceCode ? "deviceCode like '%" + this.searchParams.deviceCode + "%' and " : ""
      sqlPre += this.searchParams.deviceId ? "deviceId like '%" + this.searchParams.deviceId + "%' and " : ""
      sqlPre += this.searchParams.query ? "content like '%" + this.searchParams.query + "%' and " : ""
      sqlPre += this.level ? "level='" + this.level + "' and " : ""
      // debugger
      return sqlPre ? sqlPre.substring(0, sqlPre.length - 5) : "";
    },
    calOptSign() {
      let signParam = {}
      this.slsOptions.params = "?from=" + this.slsOptions.from + "&query=" + this.slsOptions.query + "&to=" + this.slsOptions.to + "&type=log"
      signParam.verb = "GET"
      signParam.canonicalizedResource = this.slsOptions.url + this.slsOptions.params
      signParam.date = this.slsOptions.date
      let sign = getSign(signParam);
      this.slsOptions.accessKeyId = slsParams().accessKeyId
      this.slsOptions.sign = sign
      this.slsOptions.params = this.slsOptions.params.replaceAll('%', "%25")
      console.log('signParam', this.slsOptions.params);

    },
    /**
     * 分页logstoreName
     */
    handleSizeChange(val) {
      this.slsOptions.line = val;
      this.getData();
    },
    handleCurrentChange(val) {
      this.slsOptions.offset = val - 1;
      this.getData();
    },
    /**
     * 组装opt参数
     */
    calOpt() {
      this.slsOptions.from = Math.round(this.searchParams.dateTime[0].getTime() / 1000)
      this.slsOptions.to = Math.round(this.searchParams.dateTime[1].getTime() / 1000)
      this.slsOptions.url = "/logstores/" + this.logstoreName + "/index"
      this.slsOptions.date = getGMTTime();
    },
    // 获取总数
    getTotal() {
      let _this = this;
      let whereSql = this.calSqlPre()


      this.slsOptions.query = "*|select count(1) as total" + (whereSql ? " where " + whereSql : "")
      console.log('######slsOptions', this.slsOptions);
      this.calOptSign()
      getLogStores(this.slsOptions).then(res => {
        if (res && res.data && res.data.length) {
          _this.total = parseInt(res.data[0].total)
        }
      }).catch(err => {
        // console.log(err)
        showMessage(_this, "获取Logs错误：" + err, "error")
      }).finally(()=>{
        this.$router.push({
          query:{}
        })
      });
    },
    /** 获取数据 */
    getData(obj) {
      this.listLoading = true;
      let _this = this;
      let whereSql = this.calSqlPre()
      this.slsOptions.query = "*|select currentTime,deviceCode,deviceId,level,content,tag"
        + (whereSql ? " where " + whereSql : "")
        + " order by currentTime desc limit "
        + this.slsOptions.offset * this.slsOptions.line + ","
        + this.slsOptions.line;

      this.calOptSign()
      getLogStores(this.slsOptions).then(res => {
        if (res && res.data) {
          console.log("获取到的日志数据为", res)
          _this.list = res.data
        }
      }).catch(err => {
        // console.log(err)
        this.$message.error("获取log错误" + err)
        // showMessage(_this, "获取Logs错误：" + err, "error")
      });
      this.listLoading = false;
    },
    /** 点击sls日志按钮 */
    handleClick() {
      // this.searchParams.deviceId = this.row.deviceId
      // this.searchParams.deviceCode = this.row.imei
      // let dateNow = new Date();
      // //设置时间选择默认区间
      // let dateBefore = new Date();
      // console.log(dateBefore)
      // console.log(dateBefore.getTime())
      // // 默认展示 过去六小时的数据
      // dateBefore.setTime(dateBefore.getTime() - 6 * 60 * 60 * 1000) // 毫秒，小时 * 分 * 秒
      // this.searchParams.dateTime.push(dateBefore)
      // this.searchParams.dateTime.push(dateNow);
      // this.slsLogDialog = true
      console.log('###',this.level);
      
    },
    /** 关闭sls日志弹框 */
    closeSlsLogDialog() {
      this.slsLogDialog = false
    },
  },
}
</script>
    
<style></style>